import React,{FC, useEffect, useState} from "react"
import styles from "./QuestionCheckBox.module.scss"
import { Value } from "sass"
type PropsType ={
    fe_id:string,
    props:{
        title:string,
        isVertical?:boolean
        list:Array<{
            value:string
            text:string
            checked:boolean
        }>
    }
}
const QuestionCheckBox:FC<PropsType>=({fe_id,props={}})=>{
    const {title,isVertical,list=[]} = props
    const [selectedValues,setSelectedValues] = useState<string[]>([])

    useEffect(()=>{
        list.forEach(item=>{
            const {value,checked} = item
            if(checked){
                setSelectedValues(selectedValues.concat(value))
            }
        })
    },[list])

    function toggleChecked(value:string){
       if(selectedValues.includes(value)){
        setSelectedValues(selectedValues =>selectedValues.filter(v => v!== value))
       } else{
        setSelectedValues(selectedValues.concat(value))
       }
    }
    return <>
        <p>{title}</p>
        <input type="hidden" name={fe_id} value={selectedValues.toString()} />
        <ul className={styles.list}>
        {list.map(opt=>{
            const {value,text,checked}=opt
            let liClassName =''
            if(isVertical) liClassName = styles.verticalItem
            else liClassName = styles.horizontalItem
            return <li key={value} className={liClassName}>
                <label>
                    <input 
                        type="checkbox" 
                        checked={selectedValues.includes(value)} 
                        onChange={()=> toggleChecked(value)}
                        name={fe_id}  />
                    {text}
                </label>
            </li>
        })}
        </ul>
       
    </>
}
export default QuestionCheckBox